package hip.util.db;

import java.util.Arrays;
import java.util.Map;

import com.ibatis.sqlmap.engine.impl.SqlMapClientImpl;
import com.ibatis.sqlmap.engine.mapping.sql.Sql;
import com.ibatis.sqlmap.engine.mapping.statement.MappedStatement;
import com.ibatis.sqlmap.engine.scope.SessionScope;
import com.ibatis.sqlmap.engine.scope.StatementScope;

/**
 * 根据id和参数  获取ibatis执行的sql
 *
 * @author Yejunjie
 */
public class IbatisUtils {

    public static String getSql(SqlMapClientImpl sqlclientImpl, String sqlId, Object params) {
        String sqlStr = "";
        /**获取隐身对象*/
        MappedStatement stmt = sqlclientImpl.getMappedStatement(sqlId);
        Sql sql = stmt.getSql();
        /**获取规则*/
        SessionScope sessionScope = new SessionScope();
        sessionScope.incrementRequestStackDepth();
        StatementScope statementScope = new StatementScope(sessionScope);
        stmt.initRequest(statementScope);
        /**获取sql映射对象*/
        sqlStr = sql.getSql(statementScope, params);
        return sqlStr;
    }

    public static String getRealSql(String sql, Map<String, Object> map) {
        String sql2[] = sql.split(" ");
        for (int i = 0; i < sql2.length; i++) {
            if (sql2[i].contains("=")) {
                sql2[i] = sql2[i].replace(sql2[i].split("=")[1], map.get(sql2[i].split("=")[0]).toString());
            }
        }
        return Arrays.toString(sql2).replaceAll("[\\[\\]\\s,]", " ");
    }

    public static String getRealSql(String sql, String param) {
        String sql2[] = sql.split(" ");
        for (int i = 0; i < sql2.length; i++) {
            if (sql2[i].contains("=")) {
                sql2[i] = sql2[i].replace(sql2[i].split("=")[1], param);
            }
        }
        return Arrays.toString(sql2).replaceAll("[\\[\\]\\s,]", " ");
    }

}
